package com.boot.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.boot.util.SessionUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.util.Objects;
import java.util.function.Supplier;


@Configuration
public class MyBatisPlusMetaObjectConfig implements MetaObjectHandler {

    private final SessionUtil sessionUtil;

    @Autowired
    public MyBatisPlusMetaObjectConfig(
        SessionUtil sessionUtil
    ){
        this.sessionUtil = sessionUtil;
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "gmtCreate", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "creator", String.class, sessionUtil.getUsername());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "gmtModified", LocalDateTime.class, LocalDateTime.now());
        this.strictUpdateFill(metaObject, "modifier", String.class, sessionUtil.getUsername());
    }

    /**
     * 重写，数据有值不更新改为数据有值也要更新。
     */
    @Override
    public MetaObjectHandler strictFillStrategy(MetaObject metaObject, String fieldName, Supplier<?> fieldVal) {
        Object obj = fieldVal.get();
        if (Objects.nonNull(obj))  metaObject.setValue(fieldName, obj);
        return this;
    }

}
